package com.example.HelloSpace.ui.mission_details;

import android.animation.Animator;
import android.os.Bundle;

import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager2.widget.ViewPager2;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.example.HelloSpace.MainActivity;
import com.example.HelloSpace.R;
import com.example.HelloSpace.adapters.MissionDetailsViewPagerAdapter;
import com.example.HelloSpace.factory.MissionDetailsViewModelFactory;
import com.example.HelloSpace.models.ContentModel;
import com.example.HelloSpace.service.ContentViewGenerator;
import com.example.HelloSpace.utils.MyApp;
import com.example.HelloSpace.utils.NotificationHelper;
import com.example.HelloSpace.viewmodels.MissionDetailsViewModel;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.imageview.ShapeableImageView;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.android.material.textview.MaterialTextView;


public class MissionDetailsFragment extends Fragment implements View.OnClickListener {

    private View content;
    private OnBackPressedCallback onBackPressedCallback;
    private LinearLayout contentLayout;
    private MaterialTextView title;
    private String URL;
    private View rootView;
    private ViewPager2 viewPager;
    private TabLayout tabLayout;
    private MissionDetailsViewModel viewModel;
    private int missionId;
    private String missionName;
    private MaterialButton subscribeButton;
    private boolean isSubscribed=false;

    public MissionDetailsFragment() {
        // Required empty public constructor
    }

    public static MissionDetailsFragment newInstance(String param1, String param2) {
        MissionDetailsFragment fragment = new MissionDetailsFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {

        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView= inflater.inflate(R.layout.fragment_mission_details, container, false);
        rootView.setClickable(true);
        rootView.setFocusable(true);
        title = rootView.findViewById(R.id.mtv_mission_details_title);
        content = rootView.findViewById(R.id.content);
        //contentLayout = rootView.findViewById(R.id.contentLayout);
        subscribeButton = rootView.findViewById(R.id.btn_subscribed_mission);
        AppBarLayout appBarLayout = rootView.findViewById(R.id.app_bar);
        viewPager = rootView.findViewById(R.id.view_pager);
        tabLayout = rootView.findViewById(R.id.tab_layout);
        // 在Activity中找到WebView和其容器
//        WebView liveWebView = rootView.findViewById(R.id.live_webview);
//        ViewGroup webviewContainer = rootView.findViewById(R.id.webview_container);
        postponeEnterTransition();

        //从参数中获取 missionId等参数，并创建视图模型
        if (getArguments() != null) {
            missionId = getArguments().getInt("missionID");
            missionName = getArguments().getString("missionName");

            viewModel = new ViewModelProvider(this,
                    new MissionDetailsViewModelFactory(((MainActivity) requireActivity())
                            .getMissionRepository()))
                    .get(MissionDetailsViewModel.class);
            viewModel.setContext(requireContext());

        }
        // 使用 OnGlobalLayoutListener 以确保视图布局完成
        content.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // 移除监听器，只执行一次
                content.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                // 执行入场动画
                entranceAnimation();
                // 动态加载内容
                //1.加载任务简介模块
                //contentLayout.addView(new MissionBasicInfoView(getContext()));
                //2.加载其他内容模块(先从视图模型根据id获取内容模型，再进行UI更新)
                updateUI(null); //更新UI
                viewModel.getContentModelLiveData(missionId).observe(getViewLifecycleOwner(), contentModel -> {
                    updateUI(contentModel); //更新UI
                });
            }
        });

        viewPager.setAdapter(new MissionDetailsViewPagerAdapter(requireActivity()));
        // 添加页面变化监听器
        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
            }
        });
        new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> {
            switch (position) {
                case 0:
                    tab.setText("简介");
                    break;
                case 1:
                    tab.setText("动态");
                    break;
                case 2:
                    tab.setText("相关");
                    break;
            }
        }).attach();

        viewPager.setCurrentItem(0);

//        // 设置 CollapsingToolbarLayout 的标题为空
        CollapsingToolbarLayout collapsingToolbarLayout = rootView.findViewById(R.id.collapsing_toolbar);
        collapsingToolbarLayout.setTitle("             ");

        // 设置 Toolbar
        Toolbar toolbar = rootView.findViewById(R.id.toolbar);
        ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);

        //设置订阅按钮监听
        subscribeButton.setOnClickListener(this);

        //设置AppBarLayout的折叠监听器
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            int maxScrollRange = -1;
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                // 初始化maxScrollRange为AppBarLayout的最大高度
                if (maxScrollRange == -1) {
                    maxScrollRange = appBarLayout.getTotalScrollRange();
                }

                // 计算折叠比例，范围从0到1（0表示完全展开，1表示完全折叠）
                double collapseRatio = (double) Math.abs(verticalOffset) / maxScrollRange;

                // 使用collapseRatio来动态更新UI元素
                updateControlsBasedOnCollapseRatio(collapseRatio);
            }
        });

        // 设置WebView的内容
//        WebSettings webSettings = liveWebView.getSettings();
//        webSettings.setJavaScriptEnabled(true); // 启用JavaScript支持
//        webSettings.setDomStorageEnabled(true); // 启用DOM存储API支持
//        webSettings.setUseWideViewPort(true); // 启用广泛视口，让页面适应屏幕宽度
//        webSettings.setLoadWithOverviewMode(true); // 缩放至覆盖整个屏幕
//        liveWebView.loadUrl("https://www.bilibili.com/blackboard/live/live-activity-player.html?cid=390508&quality=0");

        return rootView;
    }

    private void updateControlsBasedOnCollapseRatio(double collapseRatio) {
        if (collapseRatio < 0.8) {
            MyApp.updateStatusBarColorAndIcons(false, requireActivity());
        }
        else{
            MyApp.updateStatusBarColorAndIcons(true, requireActivity());
        }
    }

    //利用内容模型创建控件
    private void updateUI(ContentModel contentModel) {
        Log.d("MissionDetailsFragment", missionName);
        title.setText(missionName);
        if(contentModel!=null) {
            ContentViewGenerator contentViewGenerator = new ContentViewGenerator(contentLayout, getContext());
            contentViewGenerator.createView(contentModel);
        }
    }
    private void loadHeaderImage(){
        ShapeableImageView image=rootView.findViewById(R.id.header_image);
        Glide.with(image.getContext())
                .load(URL+"/images/test08.jpg")
                .centerCrop()
                .into(image);

    }
    public void entranceAnimation(){

        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        int contentViewWidth = content.getWidth();

        // 设置初始位置
        content.setTranslationX(screenWidth); // 移到屏幕右侧

        // 开始延迟转场
        startPostponedEnterTransition();

        // 执行动画
        content.animate()
                .translationX(0)
                .setDuration(250) // 设置动画时长
                .setInterpolator(new AccelerateDecelerateInterpolator())
                .withLayer()
                .setListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animator) {
                        Log.d("Animation", "Animation started");
                    }

                    @Override
                    public void onAnimationEnd(Animator animator) {
                        Log.d("Animation", "Animation ended");
                    }

                    @Override
                    public void onAnimationCancel(Animator animator) {}

                    @Override
                    public void onAnimationRepeat(Animator animator) {}
                });
    }
    public void reverseAnimation() {
        if (content != null) {
            int screenWidth = getResources().getDisplayMetrics().widthPixels;
            content.animate()
                    .translationX(screenWidth) // 移回屏幕右侧
                    .setDuration(210)
                    .setInterpolator(new AccelerateDecelerateInterpolator())
                    .withLayer()
                    .setListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animator) {
                            Log.d("Animation", "Reverse animation started");
                        }

                        @Override
                        public void onAnimationEnd(Animator animator) {
                            Log.d("Animation", "Reverse animation ended");
                            if (getActivity() != null) {
                                // 动画结束后关闭Fragment或者Activity
                                getActivity().getSupportFragmentManager().popBackStack(); // 如果是Fragment
                            }
                        }

                        @Override
                        public void onAnimationCancel(Animator animator) {}

                        @Override
                        public void onAnimationRepeat(Animator animator) {}
                    });
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        URL= MyApp.getRESOURCE_URL();
        loadHeaderImage();
        view.findViewById(R.id.btn_back).setOnClickListener(this);
        // 添加返回按钮的回调
        onBackPressedCallback = new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                // 触发退场动画
                reverseAnimation();
            }
        };
        requireActivity().getOnBackPressedDispatcher().addCallback(getViewLifecycleOwner(), onBackPressedCallback);
        // 观察按钮状态的变化
        viewModel.getIsSubscribed().observe(getViewLifecycleOwner(), isSubscribed -> {
            if (isSubscribed != null) {
                if (isSubscribed) {
                    this.isSubscribed = true;
                    subscribeButton.setText("取消订阅");
                    subscribeButton.setTextColor(getResources().getColor(R.color.white));
                    subscribeButton.setBackgroundColor(getResources().getColor(R.color.status_cancelled_or_custom));
                } else {
                    this.isSubscribed = false;
                    subscribeButton.setText("+订阅");
                    subscribeButton.setTextColor(getResources().getColor(R.color.white));
                    subscribeButton.setBackgroundColor(getResources().getColor(R.color.buttom_selected));
                }
            }
        });

        // 加载订阅状态
        viewModel.loadSubscriptionStatus(missionId);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btn_back) {
            reverseAnimation();
        }
        if(v.getId() == R.id.btn_subscribed_mission) {
            NotificationHelper.showNotification(getContext(), 3, "订阅成功", "订阅了"+missionName);
            if(!isSubscribed) {
                if(viewModel.saveSubscribedMission(viewModel.getSelectedMission().getValue())) {
                    isSubscribed = true;
                    subscribeButton.setText("取消订阅");
                    subscribeButton.setTextColor(getResources().getColor(R.color.white));
                    subscribeButton.setBackgroundColor(getResources().getColor(R.color.status_cancelled_or_custom));
                }
            }
            else{
                isSubscribed = false;
                viewModel.cancelSubscribedMission(missionId);
                subscribeButton.setText("+订阅");
                subscribeButton.setTextColor(getResources().getColor(R.color.white));
                subscribeButton.setBackgroundColor(getResources().getColor(R.color.buttom_selected));
            }
        }
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        viewModel.getIsSubscribed().removeObservers(getViewLifecycleOwner());
    }


}